package com.it.controller.admin;


import com.it.domain.UserEntity;
import com.it.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;

/**
 * @author : code1997
 * @date : 2021/9/9 22:46
 */
@Slf4j
@Controller
@RequestMapping("/admin")
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping
    public String loginPage() {
        return "admin/login";
    }

    @PostMapping("/login")
    public String login(String username, String password, HttpSession session, RedirectAttributes attributes) {
        log.info("开始执行登陆：username={},password={}", username, password);
        UserEntity userEntity = userService.checkUser(username, password);
        if (userEntity == null) {
            attributes.addFlashAttribute("message", "用户名或密码错误");
            attributes.addFlashAttribute("username", username);
            return "redirect:/admin/";
        }
        //回显的时候不能将密码打印出来.
        userEntity.setPassword(null);
        session.setAttribute("user", userEntity);
        return "admin/index";
    }

    @GetMapping("/logout")
    public String logout(HttpSession session) {
        log.info("用户：{}退出登陆.", ((UserEntity) session.getAttribute("user")).getUsername());
        session.removeAttribute("user");
        return "redirect:/admin/";
    }


}
